package org.example.doctorapi.server;

import dev.langchain4j.data.message.ChatMessage;
import dev.langchain4j.data.message.ChatMessageDeserializer;
import dev.langchain4j.data.message.ChatMessageSerializer;
import dev.langchain4j.store.memory.chat.ChatMemoryStore;
import org.mapdb.DB;
import org.mapdb.DBMaker;
import org.mapdb.Serializer;

import java.util.List;
import java.util.Map;

public class PersistentChatMemoryStore implements ChatMemoryStore {
    private final DB db = DBMaker.fileDB("./chat-memory1.db").transactionEnable().make();
    private final Map<Integer, String> map = db.hashMap("messages", Serializer.INTEGER, Serializer.STRING).createOrOpen();

    @Override
    public List<ChatMessage> getMessages(Object o) {
        String string = map.get((int) o);
        return ChatMessageDeserializer.messagesFromJson(string);
    }

    @Override
    public void updateMessages(Object o, List<ChatMessage> list) {
        String json = ChatMessageSerializer.messagesToJson(list);
        map.put((int) o,json);
        db.commit();
    }

    @Override
    public void deleteMessages(Object o) {
        map.remove((int)o);
        db.commit();
    }
}
